<!--
  角色分配弹窗组件
  @author Wu.Liang
  @date 2024-12-21
-->
<template>
    <el-dialog 
        v-model="dialogVisible" 
        title="分配角色" 
        width="600px" 
        :close-on-click-modal="false"
    >
        <div v-if="userId" class="role-assign">
            <!-- 用户信息展示 -->
            <div class="user-info-section">
                <div class="section-title">用户信息</div>
                <el-descriptions :column="2" border>
                    <el-descriptions-item label="用户名">
                        {{ currentUser?.username || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="真实姓名">
                        {{ currentUser?.realName || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="邮箱">
                        {{ currentUser?.email || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="手机号">
                        {{ currentUser?.phone || '-' }}
                    </el-descriptions-item>
                </el-descriptions>
            </div>

            <!-- 角色选择 -->
            <div class="role-section">
                <div class="section-title">选择角色</div>
                <el-form :model="formData" label-width="80px">
                    <el-form-item label="角色">
                        <el-select 
                            v-model="selectedRoleId" 
                            placeholder="请选择角色"
                            style="width: 100%"
                            @change="handleRoleChange"
                        >
                            <el-option
                                v-for="role in roleList"
                                :key="role.id"
                                :label="role.name"
                                :value="role.id"
                            >
                                <div class="role-option">
                                    <div class="role-name">{{ role.name }}</div>
                                    <div class="role-desc">{{ role.description }}</div>
                                </div>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 当前角色信息 -->
            <div v-if="currentRoleInfo" class="current-role-section">
                <div class="section-title">当前角色</div>
                <el-alert 
                    :title="`当前角色：${currentRoleInfo.name}`" 
                    type="info" 
                    :closable="false"
                    show-icon
                />
            </div>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="loading">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { assignUserRoles, getUserRoleAssignInfo } from '@/api/user'
import { showMessage } from '@/utils/message'

// Props
interface Props {
    modelValue: boolean
    userId?: number
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    'success': []
}>()

// 响应式数据
const loading = ref(false)
const selectedRoleId = ref<number | null>(null)
const currentUser = ref<any>(null)
const roleList = ref<any[]>([])

// 表单数据
const formData = ref({
    roleId: null as number | null
})

// 计算属性
const dialogVisible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
})

// 当前角色信息
const currentRoleInfo = computed(() => {
    if (!currentUser.value?.currentRoleIds?.length) return null
    const currentRoleId = currentUser.value.currentRoleIds[0]
    return roleList.value.find(role => role.id === currentRoleId)
})

watch(() => props.userId, async (newUserId) => {
    if (newUserId) {
        await loadUserRoleAssignInfo(newUserId)
    }
}, { immediate: true })

watch(() => props.modelValue, (visible) => {
    if (visible && props.userId) {
        loadUserRoleAssignInfo(props.userId)
    }
})

// 方法
const loadUserRoleAssignInfo = async (userId: number) => {
    try {
        loading.value = true
        const response = await getUserRoleAssignInfo(userId)
        const data = response.data
        currentUser.value = data
        roleList.value = (data.availableRoles || []).map((role: any) => ({
            id: role.id,
            name: role.roleName,
            description: role.description,
            status: role.status
        }))
        
        // 设置默认选中的角色
        if (data.currentRoleIds && data.currentRoleIds.length > 0) {
            // 如果有当前角色，选中第一个
            selectedRoleId.value = data.currentRoleIds[0]
        } else if (roleList.value.length > 0) {
            // 如果没有当前角色，选中最后一个
            selectedRoleId.value = roleList.value[roleList.value.length - 1].id
        } else {
            selectedRoleId.value = null
        }
        
        formData.value.roleId = selectedRoleId.value
    } catch (error: any) {
        showMessage({ type: 'error', message: '加载角色分配信息失败: ' + (error.message || error) })
    } finally {
        loading.value = false
    }
}

const handleRoleChange = (value: number) => {
    selectedRoleId.value = value
    formData.value.roleId = value
}

const handleSubmit = async () => {
    if (!props.userId) return
    if (!currentUser.value) return
    if (!selectedRoleId.value) {
        showMessage({ type: 'warning', message: '请选择角色' })
        return
    }
    
    // 判断角色是否变化
    const oldRoleId = currentUser.value.currentRoleIds?.[0] || null
    const newRoleId = selectedRoleId.value
    
    if (oldRoleId === newRoleId) {
        showMessage({ type: 'success', message: '角色分配成功' })
        emit('success')
        dialogVisible.value = false
        return
    }
    
    try {
        loading.value = true
        await assignUserRoles(props.userId, [selectedRoleId.value])
        showMessage({ type: 'success', message: '角色分配成功' })
        emit('success')
        dialogVisible.value = false
    } catch (error: any) {
        showMessage({ type: 'error', message: '角色分配失败: ' + (error.message || error) })
    } finally {
        loading.value = false
    }
}
</script>

<style scoped>
.role-assign {
    padding: 20px 0;
}

.user-info-section {
    margin-bottom: 24px;
}

.role-section {
    margin-bottom: 24px;
}

.current-role-section {
    margin-bottom: 20px;
}

.section-title {
    font-weight: 600;
    color: #303133;
    margin-bottom: 12px;
    font-size: 14px;
}

.role-option {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.role-name {
    font-weight: 500;
    color: #303133;
}

.role-desc {
    font-size: 12px;
    color: #909399;
}

.dialog-footer {
    text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .role-assign {
        padding: 10px 0;
    }
    
    .user-info-section,
    .role-section {
        margin-bottom: 16px;
    }
}
</style> 